﻿using Stee.CAP8.MessageBus.Sagas.Core;
using Stee.CAP8.MessageBus.Sagas.Core.Sagas;
using Stee.CAP8.MessageBus.Sagas.Messages.Events.Orders;
using Stee.CAP8.MessageBus.Sagas.Messages.Events.Payment;
using Stee.CAP8.MessageBus.Sagas.Order.Sagas.Data;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Stee.CAP8.MessageBus.Sagas.Order.Sagas
{
    public class OrderSaga : Saga<OrderSagaData>, IHandleMessages<OrderCreationEvent>, IHandleMessages<PayemntedEvent>
    {
        readonly IBus _bus;
        public OrderSaga(IBus bus)
        {
            _bus = bus;
        }
      /// <summary>
      /// 1
      /// </summary>
      /// <param name="message"></param>
      /// <returns></returns>
        public Task Handle(OrderCreationEvent message)
        {
            Console.WriteLine("收到订单创建" + message.ProductName);
            Data.OrderCreated = true;
            //发送支付信息到payment mircoservice
            //payment topic 
            //actionname
            _bus.PublishMessage(
                new PayemntEvent
                {
                    SagaId = Data.Id,
                    OrderId = Guid.NewGuid(),
                    PayMethod = "支付宝支付",
                    requestID = 10,
                    TotalPrice = 129.8m
                }
            );
            return Task.CompletedTask;
        }
        /// <summary>
        /// 2
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public Task Handle(PayemntedEvent message)

        {

            Data.OrderPayemnted = true;
            Console.WriteLine("已完成支付" + message.PayMethod + "||" + message.TotalPrice);
            return Task.CompletedTask;

        }

        //async Task Pre() 
        //{
        //    if (IsNew) 
        //    {
        //        CreateNewSagaData();
        //    }
        //}

        async Task Post()
        {
            if (!Data.IsDone)
            {
                return;
            }
            Console.WriteLine("订单创建完成");
            MarkAsComplete();


        }
    }
}
